package com.kzw.oa.comm.web;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.kzw.config.property.MyConfig;
import com.kzw.core.bean.Msg;
import com.kzw.core.util.IdUtils;

/**
 * 文件上传接口
 */
@Controller
@RequestMapping("/upload")
public class FileUploadAction {

	@Autowired
	private MyConfig config;

	// 禁止上传的文件类型: .jsp, .exe
	private String[] forbidSuffix = { "jsp", "exe" };
	private DateFormat df = new SimpleDateFormat("yyyyMM");
	private List<String> allowList = null;

	/**
	 * layedit图片上传接口（单文件上传）
	 * */
	@ResponseBody
	@PostMapping("image")
	public Msg upload(@RequestParam MultipartFile file, HttpServletRequest request, 
			@RequestParam(defaultValue="layedit") String category) throws IOException {
		
		Msg msg = new Msg();
		boolean flag = true;
		if (!file.isEmpty()) {
			String fname = file.getOriginalFilename();
			String ext = FilenameUtils.getExtension(fname);
			
			// 是否允许上传
			if (!canUpload(fname, allowList)) flag = false;

			// 文件上传，文件名：类型+年月
			String path = category + "/" + df.format(new Date());
			File fileDir = new File(config.getUploadDir(), path).getCanonicalFile();
			if (!fileDir.exists()) {
				FileUtils.forceMkdir(fileDir);
			}
			
			String fid = IdUtils.getIncreaseIdByCurrentTimeMillis();
			String newfname = fid + "." + ext;
			File newfile = new File(fileDir.getCanonicalPath(), newfname);
			file.transferTo(newfile);
			
			Map<String, Object> sub = new LinkedHashMap<String, Object>();
			sub.put("id", fid);	//新的文件名
			sub.put("ext", ext);
			sub.put("size", file.getSize());
			sub.put("title", fname); //原来的文件名
			sub.put("src", request.getContextPath() + "/upload/" + path + "/" + newfname);
			
			msg = new Msg(true, 0, "文件上传成功！");
			msg.setData(sub);		
		} else {
			msg = new Msg(false, 1, "没有文件上传！");
		}
		
		if(!flag) {
			msg = new Msg(false, 2, "非法文件！");
		}
		
		return msg;
	}
	
	/**
	 * 多文件上传，是否存数据库
	 * */
	@ResponseBody
	@PostMapping("file")
	public Msg multiUpload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request, 
			@RequestParam(defaultValue="other") String category) throws IOException {
		
		Msg msg = new Msg();
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		for(MultipartFile file : files) {
			if (!file.isEmpty()) {
				String fname = file.getOriginalFilename();
				String ext = FilenameUtils.getExtension(fname);
				
				// 是否允许上传
				if (!canUpload(fname, allowList)) continue;
	
				// 文件上传，文件名：类型+年月
				String path = category + "/" + df.format(new Date());
				File fileDir = new File(config.getUploadDir(), path).getCanonicalFile();
				if (!fileDir.exists()) {
					FileUtils.forceMkdir(fileDir);
				}
				
				String fid = IdUtils.getIncreaseIdByCurrentTimeMillis();
				String newfname = fid + "." + ext;
				File newfile = new File(fileDir.getCanonicalPath(), newfname);
				file.transferTo(newfile);
				
				Map<String, Object> sub = new LinkedHashMap<String, Object>();
				sub.put("id", fid);	//新的文件名
				sub.put("ext", ext);
				sub.put("size", file.getSize());
				sub.put("title", fname); //原来的文件名
				sub.put("src", request.getContextPath() + "/upload/" + path + "/" + newfname);
				list.add(sub);				
			}
		}
		
		if(list.size() > 0) {
			msg = new Msg(true, 0, "文件上传成功！");
			msg.setData(list);
		} else {
			msg = new Msg(false, 1, "没有文件上传！");
		}
		
		return msg;
	}

	/**
	 * 是否允许访问
	 */
	public boolean canUpload(String fname, List<String> allowList) {
		// 文件是否有后缀名
		String ext = FilenameUtils.getExtension(fname);
		if (ext.equals(""))
			return false;
		// 如果是禁止访问类型
		if (Arrays.asList(forbidSuffix).contains(ext)) {
			return false;
		}
		// 如果没有设置allow_perm，则默认开放
		if (allowList == null || allowList.size() == 0) {
			return true;
		}
		// 允许访问
		if (allowList.contains(ext)) {
			return true;
		}
		return false;
	}

}
